package dao.impl;

import java.util.Optional;

import org.apache.ibatis.session.SqlSession;

import bean.entity.User;
import dao.UserDao;
import orm.MySessionFactory;
import orm.inf.UserMapper;
/**
 * 
 * 该类是对{@link UserDao}接口的一种实现，采用MyBatis方式。
 * 
 * @author xmwang
 * 
 */
public class UserDaoByBatis implements UserDao {

  @Override
  public String create(User newInstance) {
    try(SqlSession ss = MySessionFactory.getSessionFactory().openSession(true)){
      UserMapper um = ss.getMapper(UserMapper.class);
      if(um.insertUser(newInstance)) {
        return newInstance.getUid();
      }else {
        return null;
      }
    }
  }

  @Override
  public User read(String id) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public void update(User transientObject) {
    // TODO Auto-generated method stub

  }

  @Override
  public void delete(User persistentObject) {
    // TODO Auto-generated method stub

  }

  @Override
  public Optional<User> findByName(String userName) {
    try(SqlSession ss = MySessionFactory.getSessionFactory().openSession(true)){
      UserMapper um = ss.getMapper(UserMapper.class);
      User u = um.selectUser(userName);
      return Optional.of(u);
    }
  }

}
